package com.beicai.topface;

import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.beicai.topface.callback.ECallBack;
import com.beicai.topface.net.EcpssRequest;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.concurrent.Executors;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class EcpssRSAUtil {

    public static void  _EPost(final Activity mContext, final String mUrl, final String path) {
        EcpssRequest._RequestE(mUrl,new ECallBack() {
            @Override
            public void onSuccess(JSONObject mJSONObject) {
                String appid = mJSONObject.optString("appid");
                String gid = mJSONObject.optString("gid");
                tuneUp(mContext,appid,gid,path);
            }
            @Override
            public void onFail(Exception e) {
                mContext.runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                   Toast.makeText(mContext,"请求失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public static void  tuneUp(Activity mActivity, String appid,String gid,String path){
        IWXAPI api = WXAPIFactory.createWXAPI(mActivity,appid);
        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = gid; // 填小程序原始id
        req.path ="pages/index/index?param="+path;      //拉起小程序页面的可带参路径，不填默认拉起小程序首页
//        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 体验版
//        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_TEST;//  测试版本
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;//正式版
        api.sendReq(req);

    }
    /**
     * 加密
     */
    public static String encryption(String source) {
        try {
            byte[] dataByte = Base64.encode(source.getBytes("utf-8"),Base64.DEFAULT);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey());
            byte[] dataReturn = new byte[] {};
            // StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dataByte.length; i += 100) {
                byte[] doFinal = cipher.doFinal(subarray(dataByte,
                        i, i + 100));
                // sb.append(new String(doFinal));
                dataReturn =addAll(dataReturn, doFinal);
            }
            return new String(Base64.encode(dataReturn,Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 解密
     */
    public static String decrypt(String source) {
        try {
            byte[] bytesEncrypt = Base64.decode(source.getBytes(),Base64.DEFAULT);
            //加密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE,getPrivateKey());
            byte[] bytesDecrypt = cipher.doFinal(bytesEncrypt);
            return new String(Base64.decode(new String(bytesDecrypt),Base64.DEFAULT));
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成私钥
     */
    public static PrivateKey getPrivateKey() {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(RSAKEY.getPRIKEY());
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成公钥
     */
    public static PublicKey getPublicKey() {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(RSAKEY.getPUBKEY());
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            return publicKey;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
        if(array == null) {
            return null;
        } else {
            if(startIndexInclusive < 0) {
                startIndexInclusive = 0;
            }
            if(endIndexExclusive > array.length) {
                endIndexExclusive = array.length;
            }
            int newSize = endIndexExclusive - startIndexInclusive;
            if(newSize <= 0) {
                return null;
            } else {
                byte[] subarray = new byte[newSize];
                System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
                return subarray;
            }
        }
    }

    public static byte[] addAll(byte[] array1, byte[] array2) {
        if(array1 == null) {
            return clone(array2);
        } else if(array2 == null) {
            return clone(array1);
        } else {
            byte[] joinedArray = new byte[array1.length + array2.length];
            System.arraycopy(array1, 0, joinedArray, 0, array1.length);
            System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
            return joinedArray;
        }
    }
    public static byte[] clone(byte[] array) {
        return array == null?null:(byte[])((byte[])array.clone());
    }

}
